package com.yzj.android.servlet;

import com.google.gson.Gson;
import com.yzj.Bean.Cake;
import com.yzj.android.service.CakeService;
import com.yzj.android.service.impl.CakeServiceImpl;
import com.yzj.android.utils.WebUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class CakeServlet extends BaseServlet {

    private CakeService cakeService = new CakeServiceImpl();
    private Gson gson = new Gson();
    private List<Cake> list = new ArrayList<>();

    protected void list(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        list = cakeService.queryCakes();
        //发送JSON 数据给前台
        String listJson = gson.toJson(list);
        // list 转为json  字符串
        // 返回客户端的是字符串
        // 客户端再转为json 对象
        resp.setHeader("Content-type", "text/html;charset=UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.getWriter().write(listJson);
    }

    protected void queryCakeInfo(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //得到  搜索 信息
        String string = req.getParameter("string");
        String listJson = gson.toJson(cakeService.queryCakeinfo(string));
        //发送JSON 数据给前台
        resp.setHeader("Content-type", "text/html;charset=UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.getWriter().write(listJson);
    }


    //删除商品
    protected void delCake(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //得到  搜索 信息
        int id = WebUtils.StringToInt(req.getParameter("id"), 0);
        cakeService.deleteCakeById(id);
        resp.setHeader("Content-type", "text/html;charset=UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.getWriter().write("删除成功");
    }

    //修改商品


    protected void updateCake(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        Cake cake = WebUtils.copyParamToBean(req.getParameterMap(),
                new Cake());


        cakeService.updateCake(cake);
        resp.setHeader("Content-type", "text/html;charset=UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.getWriter().write("成功");
    }
    protected void addCake(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Cake cake = WebUtils.copyParamToBean(req.getParameterMap(),
                new Cake());
        System.out.println(cake);
        cakeService.addCake(cake);
    }

}

